
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
import datetime
import json

from todoism.extensions import db


class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, index=True)
    password_hash = db.Column(db.String(128))
    locale = db.Column(db.String(20))
    items = db.relationship('Item', back_populates='author', cascade='all')
    backups = db.relationship('Backup', back_populates='user', cascade='all')

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def validate_password(self, password):
        return check_password_hash(self.password_hash, password)


class Item(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    body = db.Column(db.Text, nullable=False)
    done = db.Column(db.Boolean, default=False)
    deadline = db.Column(db.DateTime, nullable=True)  # 截止时间字段
    # due_date = db.Column(db.Date, nullable=True)  # 添加日期字段（已注释）
    order = db.Column(db.Integer, default=0, index=True, nullable=False)  # 新增排序字段
    category = db.Column(db.String(20), default='Other')  # 任务分类：Work, Life, Study, Game, Other
    author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    author = db.relationship('User', back_populates='items')
    
    def to_dict(self):
        """将任务转换为字典，用于备份"""
        return {
            'id': self.id,
            'body': self.body,
            'done': self.done,
            'deadline': self.deadline.isoformat() if self.deadline else None,
            'order': self.order,
            'category': self.category
        }


class Backup(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    timestamp = db.Column(db.DateTime, default=datetime.datetime.now, index=True)
    data = db.Column(db.Text, nullable=False)  # 存储任务列表的JSON字符串
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    user = db.relationship('User', back_populates='backups')
    
    @property
    def created_time(self):
        """格式化的创建时间"""
        return self.timestamp.strftime('%Y-%m-%d %H:%M:%S')
    
    def save_items(self, items):
        """将任务列表保存为JSON字符串"""
        items_data = [item.to_dict() for item in items]
        self.data = json.dumps(items_data)
